# coding: utf8

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, QueryDict, HttpResponseRedirect
from django.template import Context, loader
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse
from django.views.generic import View, TemplateView
import logging
from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required
from django.conf import settings

logger = logging.getLogger("opsweb")

# Create your views here.

def hello(request):
    data = { "name": "tom", "age": 25 }
    data_list = [ "a", "b", "c" ]
    #return HttpResponse("<h1>hello world !!! 世界， 你好！！！</h1>")
    #return JsonResponse(data)
    return JsonResponse(data_list, safe=False)

class LoginView(TemplateView):
    template_name = 'user/login.html'
    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        context["title"] = "reboot 运维平台"
        return context
    def post(self, request, *args, **kwargs):
        ret = {"status": 0}
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request, user)
                ret['next_url'] = '/'
            else:
                ret['status'] = 1
                ret['errmsg'] = "该用户被禁用"
        else:
            ret["status"] = 2
            ret['errmsg'] = "用户名或密码错误"
        return JsonResponse(ret, safe=True)

# def login_view(request):
#     #template = loader.get_template('user/login.html')
#     #context = Context({"title": "reboot 运维平台"})
#     #context = RequestContext(request, {"title": "reboot 运维平台"})
#     #return HttpResponse(template.render(context))
#     if request.method == "GET":
#         return render(request, 'user/login.html', {"title": "reboot 运维平台"})
#     elif request.method == "POST":
#         ret = { "status": 0}
#         username = request.POST.get("username", "")
#         password = request.POST.get("password", "")
#         print username, password
#         user = authenticate(username=username, password=password)
#         if user:
#             if user.is_active:
#                 login(request, user)
#                 ret['next_url'] = '/'
#             else:
#                 ret['status'] = 1
#                 ret['errmsg'] = "该用户被禁用"
#         else:
#             ret["status"] = 2
#             ret['errmsg'] = "用户名或密码错误"
#         return JsonResponse(ret, safe=True)

class LogoutView(View):
    def get(self, request, *args, **kwargs):
        print("call logout")
        logout(request)
        return HttpResponse("用户已退出")

# def logout_view(request):
#     logout(request)
#     return HttpResponse("用户已退出")

def test_form(request):
    if request.method == "GET":
        return render(request, 'test/test_form.html')
    elif request.method == "POST":
        # print request.POST
        # #<QueryDict: {u'username': [u'rock'], u'fav': [u'1', u'2']}>
        # username = request.POST.get('username', "")
        # print username #rock
        # # fav = request.POST.get('fav')
        # # print fav #2
        # # fav = request.POST.getlist('fav', [])
        # # print fav  # [u'1', u'2']
        # # all = request.POST.lists()
        # # print all #[(u'username', [u'rock']), (u'fav', [u'1', u'2'])]
        # # all = request.POST.dict()
        # # print all #{u'username': u'rock', u'fav': u'2'}
        print request.body #username=rock&fav=1&fav=2
        return HttpResponse("")
    elif request.method == 'PUT':
        print request.body #username=rock&fav%5B%5D=1&fav%5B%5D=2
        print QueryDict(request.body) #<QueryDict: {u'username': [u'rock'], u'fav[]': [u'1', u'2']}>
        return HttpResponse("")

class IndexView(View):
    @method_decorator(login_required)
    @method_decorator(permission_required("dashboard.view_server", login_url=settings.PERMISSION_NONE_URL))
    def get(self, request):
        return render(request, "public/index.html")

def permission(request):
    return render(request, "public/permission.html")